package com.atguigu.gmall.mq.receiver;

import com.atguigu.gmall.mq.config.DeadLetterMqConfig;
import com.atguigu.gmall.mq.config.DelayedMqConfig;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author Fxz
 * @version 1.0
 * @date 2022-02-20 16:58
 */
@Slf4j
@Component
public class ConfirmReceiver {

	/**
	 * 监听消息
	 */
	@SneakyThrows
	@RabbitListener(
			bindings = @QueueBinding(value = @Queue(value = "queue.confirm", durable = "true", autoDelete = "false"),
					exchange = @Exchange(value = "exchange.confirm"), key = { "routing.confirm" }))
	public void getMessage(String msg, Message message, Channel channel) {
		log.info("接收到的消息:{}\n{}", msg, new String(message.getBody()));
		// 手动ack
		long deliveryTag = message.getMessageProperties().getDeliveryTag();
		// true表示批量ack false表示一个一个ack
		channel.basicAck(deliveryTag, false);
	}

	@RabbitListener(queues = { DeadLetterMqConfig.queue_dead_2 })
	public void getMsg(String msg, Message message, Channel channel) throws IOException {
		log.info("接收到的消息:{}", msg);
		log.info("当前时间:{}", LocalDateTime.now());
		// 手动ack
		long deliveryTag = message.getMessageProperties().getDeliveryTag();
		// true表示批量ack false表示一个一个ack
		channel.basicAck(deliveryTag, false);
	}

	@RabbitListener(queues = { DelayedMqConfig.queue_delay_1 })
	public void getMsg2(String msg, Message message, Channel channel) throws IOException {
		log.info("接收到的消息:{}", msg);
		log.info("当前时间:{}", LocalDateTime.now());
		// 手动ack
		long deliveryTag = message.getMessageProperties().getDeliveryTag();
		// true表示批量ack false表示一个一个ack
		channel.basicAck(deliveryTag, false);
	}

}
